import { useState, useCallback } from "react";
import { Text, View, ScrollView, useWindowDimensions, StyleSheet, TouchableOpacity } from "react-native";
import AntDesign from "react-native-vector-icons/AntDesign";

import type { StyleProp, ViewStyle } from "react-native";
import type { Props as ModalBoxProps } from "@/components/ModalBox";

import ModalBox from "@/components/ModalBox";

export type StateType = {
  /** 查看的数据 */
  list: any[];
  /** modal box 显示/隐藏 */
  visible: boolean;
};

/** ShowItemField 类型 */
export type ShowItemFieldItem = {
  /** 显示的label */
  label: string;
  /** 显示的label */
  value: (item: any, index: number, props: Props) => string | number | React.ReactNode;
};

export type Props = {
  /** 是否显示数据右上角的关闭 */
  showDel: boolean;
  /** ModalBox 配置 */
  modalBoxProps: Omit<ModalBoxProps, "visible">;
  /** 内容之前的样式 */
  ComtentBefore?: () => React.ReactNode;
  /** 数据的键 */
  dataKey?: string;
  /** 打开弹框之前 */
  openModelBoxAfter?: (list: any[]) => any[];
  /** 自定义item内容, 注意需要绑定 key */
  getItem?: (item: any, index: number, props: Props) => React.ReactNode;
  /** 默认样式显示字段 */
  getShowItemField?: () => ShowItemFieldItem[];
  /** 没一项的容器样式 */
  getItemStyle?: (item: any, index: number, props: Props) => StyleProp<ViewStyle>;
  /** item点击事件 */
  itemClick?: (item: any, index: number, props: Props) => void;
  /** 底部组件 */
  getBottomComp?: () => React.ReactNode;
};

/** 查看资产详细信息 */
export default (props: Props) => {
  const [state, _setState] = useState<StateType>({
    list: [],
    visible: false
  });

  // 通用更新状态单个
  const setState = useCallback((field: keyof typeof state, val: any) => {
    _setState(_state => {
      return { ..._state, [field]: val };
    });
  }, []);

  // 通用更新状态(对象)
  const setObjState = useCallback((obj: Partial<typeof state>) => {
    _setState(_state => {
      return { ..._state, ...obj };
    });
  }, []);

  const windowDimensions = useWindowDimensions();

  /** 查看数据 */
  const open = (list: any[]) => {
    setObjState({ list, visible: true });
  };

  /** 处理点击事件 */
  const handleItemClick = (item: any, i: number) => {
    props.itemClick && props.itemClick(item, i, props);
  };

  /** modal box 组件 */
  const EquipmentModalBox = (
    <ModalBox
      visible={state.visible}
      dismissable={false}
      onClose={() => setState("visible", false)}
      {...props.modalBoxProps}
    >
      {props.ComtentBefore && props.ComtentBefore()}
      <ScrollView style={{ maxHeight: windowDimensions.height * 0.6, width: "100%" }}>
        {state.list.map((e, index) => {
          const dataKey = props.dataKey || "id";
          const ItemComp = props.getItem ? (
            <View key={(e as any)[dataKey]}>{props.getItem(e, index, props)}</View>
          ) : (
            <TouchableOpacity
              key={(e as any)[dataKey]}
              style={[styles.item, props.getItemStyle ? props.getItemStyle(e, index, props) : null]}
              onPress={() => handleItemClick(e, index)}
            >
              {props.getShowItemField &&
                props.getShowItemField().map((item, i) => (
                  <Text key={i}>
                    {item.label}: {item.value(e, index, props)}
                  </Text>
                ))}

              {props.showDel && (
                <TouchableOpacity
                  style={styles.itemCloseContainer}
                  onPress={() => {
                    const newList = state.list.filter(item => item[dataKey] !== e[dataKey]);
                    setObjState({
                      list: [...newList],
                      visible: newList.length > 0
                    });
                  }}
                >
                  <AntDesign name="close" style={styles.itemCloseIcon} />
                </TouchableOpacity>
              )}
            </TouchableOpacity>
          );

          return ItemComp;
        })}
      </ScrollView>
      {props.getBottomComp && props.getBottomComp()}
    </ModalBox>
  );

  return {
    open,
    close: () => setObjState({ visible: false }),
    Comp: EquipmentModalBox,
    list: state.list
  };
};

const styles = StyleSheet.create({
  item: {
    marginTop: 6,
    marginBottom: 6,
    backgroundColor: "#f0f0f0",
    padding: 4,
    borderRadius: 4
  },
  itemCloseContainer: {
    position: "absolute",
    right: 4,
    top: 4,
    backgroundColor: "white",
    padding: 4,
    borderRadius: 4
  },
  itemCloseIcon: {
    fontSize: 16,
    color: "#282c34"
  }
});
